package com.example.springinitialization.interception;

import com.example.springinitialization.annotation.AuthCheck;
import com.example.springinitialization.constant.ErrorCode;
import com.example.springinitialization.exception.MyException;
import com.example.springinitialization.pojo.vo.User;
import com.example.springinitialization.service.UserService;
import com.example.springinitialization.utils.token.LoginUserUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;

import javax.annotation.Resource;

public class AuthInterceptor {

    @Resource
    UserService userService;

    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String role = authCheck.auth();
        // 写上了注解，就必须要有值
        if(role == null || "".equals(role)) {
            throw new MyException(ErrorCode.NO_AUTH_ERROR);
        }
        // 获取当前登录用户
        User user = LoginUserUtils.getUser();
        if(user == null) {
            throw new MyException(ErrorCode.NOT_LOGIN_ERROR);
        }
        if(!role.equals(user.getRole())) {
            // 权限不符合，无权限
            throw new MyException(ErrorCode.NO_AUTH_ERROR);
        }
        // 通过校验，放行
        return joinPoint.proceed();
    }
}
